﻿using DotNetMVC.OA.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DotNetMVC.OA.EFDAL
{
   public class BaseDal<T> where T:class,new()
    {
        //DataModelContainer db = new DataModelContainer();

        public DbContext Db
        {
            get { return DbContextFactory.GetCurrentDbContext(); }
        }

        //crue
        #region 查询
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
        {
            return Db.Set<T>().Where(whereLambda).AsQueryable();
        }

        public IQueryable<T> GetPageEntities<S>(
            int pageSize, int pageIndex, out int total,
            Expression<Func<T, bool>> whereLambda,
            Expression<Func<T, S>> orderByLambda,
            bool isAsc
            )
        {
            var temp = Db.Set<T>().Where(whereLambda);
            total = temp.Count();

            if (isAsc)  //升序 OrderBy
            {
                temp = temp.OrderBy<T, S>(orderByLambda)
                      .Skip(pageSize * (pageIndex - 1))
                      .Take(pageSize)
                      .AsQueryable();
            }
            else //降序  OrderByDescending
            {
                temp = temp.OrderByDescending<T, S>(orderByLambda)
                      .Skip(pageSize * (pageIndex - 1))
                      .Take(pageSize)
                      .AsQueryable();
            }

            return temp;
        }
        #endregion

        #region cud
        public T Add(T Entity)
        {
            Db.Set<T>().Add(Entity);
            //Db.SaveChanges();
            return Entity;
        }
        public bool Update(T Entity)
        {
            Db.Entry(Entity).State = EntityState.Modified;
            //return Db.SaveChanges() > 0;
            return true;
        }
        public bool Delete(T Entity)
        {
            //Db.Entry(Entity).State = EntityState.Deleted;
            //return Db.SaveChanges() > 0;

            Db.Entry(Entity).Property("DelFlag").CurrentValue = (short)Model.Enum.DelFlagEnum.Deleted;
            Db.Entry(Entity).Property("DelFlag").IsModified = true;

            return true;
        }
        public bool Delete(long id)
        {
            T Entity = Db.Set<T>().Find(id);
            Delete(Entity);
            return true;
        }
        #endregion
    }
}
